package com.fingard.dsp.bank.directbank.bocom12;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAcceptNotice;
import com.fingard.dsp.bank.directbank.bocom13.util.MD5;
import com.fingard.generalobj.NoticeReq;
import com.fingard.generalobj.NoticeResp;
import com.fingard.net.listener.SocketReceiver;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

public class BOCOM12AcceptNotice extends BOCOM12Base implements IAcceptNotice {
	@SuppressWarnings({ "resource", "unused" })
	@Override
	public NoticeResp dealNotice(NoticeReq pNtReq) throws Exception {
		
		NoticeResp resp = new NoticeResp();
    	String p_req = pNtReq.getReqString();
    	WriteBankLogLn("接收到请求：" + pNtReq.getFullString());

		byte[] bytesBkRet = pNtReq.reqBytes;
		String transCode = new String(bytesBkRet, 24, 6);
		WriteBankLogLn("银行通知交易码:" + transCode);

		boolean ifContinue = false;
		String retBkStr = "";
		String zipFileName = "";
		int zipFileSize = 0;
		String zipFileMD5 = "";
		int askBlockSeq = 0;
		if ("B60901".equals(transCode) || "I60901".equals(transCode)) {
			String bkTransSeq = new String(bytesBkRet, 85, 20);
			WriteBankLogLn("交易流水号:" + bkTransSeq);

			zipFileName = new String(bytesBkRet, 119, 128);
			WriteBankLogLn("压缩文件名称:" + zipFileName);

			zipFileSize = Integer.parseInt(new String(bytesBkRet, 247, 12));
			WriteBankLogLn("文件大小:" + zipFileSize);

			zipFileMD5 = new String(bytesBkRet, 267, 200);
			WriteBankLogLn("文件MD5校验值:" + zipFileMD5);

			WriteBankLogLn("初始文件块序号:" + askBlockSeq);
			retBkStr = "G000000";
			ifContinue = true;
		} else if ("B60902".equals(transCode)) {
			String tmpStrReqHead = new String(bytesBkRet, 0, 36);
			WriteBankLogLn("接收到【报文3】请求头部:" + tmpStrReqHead);

			String tmpPck5Tail = Format.Date8Format.format(new Date()) + String.format("%20s", Format.DateTime17Format.format(new Date())).replace(" ", "0");
			int tmpBkSeq = Integer.parseInt(new String(bytesBkRet, 30, 6));
			WriteBankLogLn("当前报文3中块序号:" + tmpBkSeq);
			if (askBlockSeq == tmpBkSeq) {
                FileOutputStream localFileStream = null;
			    try {

                    String tmpDir = getPrepareDataDirectory();
                    String localFileName = tmpDir + File.separator + zipFileName;
                    WriteBankLogLn("保存到本地文件名:" + localFileName);
                    if (new File(localFileName).exists()) {
                        WriteBankLogLn("本地文件已存在...");
                    } else {
                        WriteBankLogLn("本地文件不存在...");
                    }
                    localFileStream = new FileOutputStream(new File(localFileName));
                    byte[] tmpBytes = new byte[bytesBkRet.length - 36];
                    System.arraycopy(bytesBkRet, 36, tmpBytes, 0, bytesBkRet.length - 36);
                    localFileStream.write(tmpBytes);
                    int fileByteWriteCount = bytesBkRet.length - 36;
                    WriteBankLogLn("当前数据包字节大小:" + fileByteWriteCount);
                    if (fileByteWriteCount >= zipFileSize) {
                        WriteBankLogLn("实际压缩包文件byte总长度:|" + fileByteWriteCount + "|");
                        WriteBankLogLn("报文中压缩包文件byte总长度:|" + zipFileSize + "|");
                        if (fileByteWriteCount != zipFileSize) {
                            retBkStr = "E000009" + String.format("%-300s", "实际写入文件字节数" + fileByteWriteCount + "不等于预期文件字节数" + zipFileSize) + tmpPck5Tail;
                        } else {
                            String tmpGZMD5 = MD5.generateFileMD5(localFileName);
                            WriteBankLogLn("实际MAC:|" + tmpGZMD5 + "|");
                            WriteBankLogLn("报文中MAC:|" + zipFileMD5 + "|");
                            if (zipFileMD5 == tmpGZMD5) {
                                StringBuilder tmpSbPck1 = new StringBuilder();
                                tmpSbPck1.append("N");
                                tmpSbPck1.append("000000");
                                tmpSbPck1.append(String.format("%-300s", "文件传输成功"));
                                tmpSbPck1.append(Format.Date8Format.format(new Date()));
                                tmpSbPck1.append(String.format("%-20s", Format.DateTime17Format.format(new Date())).replace(" ", "0"));
                                tmpSbPck1.append(String.format("%-1500s", ""));
                                retBkStr = tmpSbPck1.toString();
                            } else {
                                StringBuilder tmpSbPck1 = new StringBuilder();
                                tmpSbPck1.append("E");
                                tmpSbPck1.append("000009");
                                tmpSbPck1.append(String.format("%-300s", "MD5校验失败，本地产生的MD5为"));
                                tmpSbPck1.append(Format.Date8Format.format(new Date()));
                                tmpSbPck1.append(String.format("%-20s", Format.DateTime17Format.format(new Date())).replace(" ", "0"));
                                tmpSbPck1.append(String.format("%-1500s", ""));
                                retBkStr = tmpSbPck1.toString();
                            }
                        }
                    } else {
                        askBlockSeq = askBlockSeq + 1;
                        WriteBankLogLn("当前文件块序号:" + askBlockSeq);
                        retBkStr = "G" + String.format("%06d", askBlockSeq);
                        ifContinue = true;
                    }

                }catch (Exception e) {
                    System.out.println(e.getMessage());
                } finally {
			        if (localFileStream != null) {
			            localFileStream.close();
                    }
                }
			} else {
				StringBuilder tmpSbPck1 = new StringBuilder();
				tmpSbPck1.append("E");
				tmpSbPck1.append("000001");
				tmpSbPck1.append(String.format("%-300s", "请求数据包：" + askBlockSeq + "，但银行返回" + tmpBkSeq));
				tmpSbPck1.append(Format.Date8Format.format(new Date()));
				tmpSbPck1.append(String.format("%-20s", Format.DateTime17Format.format(new Date())).replace(" ", "0"));
				tmpSbPck1.append(String.format("%1500s", ""));
				retBkStr = tmpSbPck1.toString();
			}
		} else {
			StringBuilder tmpSbPck1 = new StringBuilder();
			tmpSbPck1.append("E");
			tmpSbPck1.append("000001");
			tmpSbPck1.append("E000001" + String.format("%-300s", "不支持的交易码：" + transCode));
			tmpSbPck1.append(Format.Date8Format.format(new Date()));
			tmpSbPck1.append(String.format("%-20s", Format.DateTime17Format.format(new Date())).replace(" ", "0"));
			tmpSbPck1.append(String.format("%-1500s", ""));
			retBkStr = tmpSbPck1.toString();
		}
		
		WriteBankLogLn("响应："+ retBkStr);
        resp.respBytes = retBkStr.getBytes(pNtReq.reqCharset);
    	return resp;
	}

	@Override
	public void getContentLength(SocketReceiver p_receiver) throws Exception {
		if (p_receiver.contentLength == -1) {
			if (p_receiver.readedLength >= 24) {
				p_receiver.contentLength = Integer.parseInt(new String(p_receiver.reqBytes, 0, 8, getCharset())) - 16;
				p_receiver.contentStartIndex = 24;
			}
		}
	}
}
